package com.obixlabs.commons.process;

import static com.obixlabs.commons.process.MemoryFormatter.formatMemory;

import java.text.DateFormat;
import java.time.Instant;
import java.util.Date;

public class ProcessUtil {

	private static final DateFormat HEARTBEAT_TIME_FORMAT = 
				DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
	
	public static String getHeartbeatMessage(String processName) {
		StringBuffer result = new StringBuffer(processName + " heartbeat at ");
		result	.append(HEARTBEAT_TIME_FORMAT.format(Date.from(Instant.now())))
					.append(". " + getMemoryInfo());
		return result.toString();
	}
	
	private static String getMemoryInfo() {
		StringBuffer result = new StringBuffer("Memory info: ");
		double totalMemory = Runtime.getRuntime().totalMemory();		
		double freeMemory = Runtime.getRuntime().freeMemory();		
		long percent = Math.round((freeMemory/totalMemory) * 100);
		result	.append(formatMemory(freeMemory) +" of " )
					.append(formatMemory(totalMemory) +" (" + percent + "%) free.");
		return result.toString();		
	}
}